const uniID = require('uni-id-common');

exports.main = async (event, context) => {
	// 解析请求体
	let body = event;
	if (event.body !== undefined) {
	  try {
	    body = JSON.parse(event.body);
	  } catch (e) {
	    return {
	      code: 400,
	      message: "请求体解析失败",
	      error: e.message
	    };
	  }
	}
	
	const db = uniCloud.database();
	const dbCmd = db.command;

	const {
		searchKeyword = '',
		page = 1,
		pageSize = 10,
		sortField = 'create_date',
		sortOrder = 'desc'
	} = body;
	
	// 校验 sortField 是否为允许的字段
	const validSortFields = ['rating', 'experience', 'create_date'];
	if (!validSortFields.includes(sortField)) {
	  return {
	    code: 400,
	    message: '参数 sortField 只能为 rating、experience 或 create_date'
	  };
	}
	
	const uniIDIns = uniID.createInstance({ context });

	// 构建查询条件：模糊匹配姓名
	const where = {};
	if (searchKeyword.trim() !== '') {
		where.name = new RegExp(searchKeyword, 'i'); // 不区分大小写的正则匹配
	}

	const skip = (page - 1) * pageSize;

	// 查询总数用于分页
	const totalRes = await db.collection('consultants').where(where).count();
	const total = totalRes.total;
	const totalPages = Math.ceil(total / pageSize);

	// 查询数据
	const res = await db.collection('consultants')
		.where(where)
		.orderBy(sortField, sortOrder)
		.skip(skip)
		.limit(pageSize)
		.get();

	let consultants = res.data || [];
	if (Array.isArray(consultants)) {
		consultants = await Promise.all(consultants.map(async (item) => {
			if (item.user_id) {
				const { token } = await uniIDIns.createToken({ uid: item.user_id });
				const { user_id, ...rest } = item;
				return { ...rest, uniIdToken: token };
			}
			return item;
		}));
	}

	return {
		code: 0,
		data: {
			consultants,
			page,
			pageSize,
			total,
			totalPages
		}
	};
};
